<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 13:22
 */
namespace app\api\controller\v1;

use app\api\model\UserAddress;
use app\api\service\Token as ServiceToken;
use app\api\validate\AddressCheck;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use think\Controller;
use app\api\model\User as UserModel;
use think\Request;

class Address extends Controller {

    protected $beforeActionList = [
        'checkprimaryscope'=>['only'=>'createorupdateaddress']
    ];

    /**
     * 前置方法，验证权限级别
     */
    public function checkPrimaryScope(){
        $scope = ServiceToken::getCurrentTokenVar('scope');
        if($scope){
            if($scope >= ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }


    public function createOrUpdateAddress(){
        (new AddressCheck())->goCheck();
//        根据token获取用户uid
//        使用uid查找用户是否存在，如果不存在就抛出异常
//         获取用户从客户端来的用户信息
//        根据用户地址信息是否存在来添加或更新地址
        $uid = ServiceToken::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        $request = Request::instance();
        $dataArray = $request->except(['version']);
        $userAddress = UserModel::getUserAddress();
        $addressModel = new UserAddress();
        if(empty($userAddress->address)){
//            添加地址
            $dataArray['user_id'] = $uid;
            $addressModel->save($dataArray);
        }else{
//            更新地址
            $addressModel->save($dataArray,['user_id'=>$uid]);
        }
        return json(['code'=>200,'msg'=>'OK','data'=>$addressModel]);
    }

}












